package main.database;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Updates;
import main.GlobalConfig;
import org.bson.Document;
import org.bson.conversions.Bson;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Updates.set;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class ScoreHelper {
    /**
     * 作用：该方法通过指定的uuid（用户），bookId（小说），来查看该用户对小说的评分
     * @param uuid: 用户的uuid
     * @param articleId: 小说的id，这个id是每篇小说的ObjectId的toString()结果
     * @return float (-1：用户对指定小说没有评分；其他：评分）
     */
    public static double getUserScore(String uuid, String articleId) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUserScore);
//        AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
//                new Document("$match", new Document("uuid", uuid)),
//                new Document("$match", new Document("fictionId", articleId))
//        ));

        Bson filter = and(eq("uuid", uuid), eq("fictionId", articleId));
        FindIterable<Document> findIterable = collection.find(filter);

        double score = 0.0;
        MongoCursor<Document> cursor = findIterable.iterator();
        if (cursor.hasNext()) {
            score = (double) cursor.next().get("score");
        }
        cursor.close();

        return score;
    }

    /**
     *
     * @param uuid, 用户的uuid
     * @param score，用户提交的分数
     * @return int，0：表示非更新操作；1：表示本次是更新了原来的分数；-1: 表示唯有用户登录信息；
     */
    public static int submitScore(String uuid, String articleId, float score) {
        int result = -1;

        if (uuid != null && !uuid.isEmpty()) {
            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUserScore);
            FindIterable<Document> documents = collection.find(and(eq("uuid", uuid), eq("fictionId", articleId)));
            MongoCursor<Document> cursor = documents.iterator();

            if (cursor.hasNext()) {
                Bson filter = and(eq("uuid", uuid), eq("fictionId", articleId));
                Bson update = set("score", score);
                collection.updateOne(filter, update);
                result = 1;
            }
            else {
                Document document = new Document("uuid", uuid)
                        .append("fictionId", articleId)
                        .append("score", score);
                collection.insertOne(document);

                //给用户加分
                collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUser);
                Bson filter = new Document("uuid", uuid);
                Bson update = Updates.inc("money", 2);
                collection.updateOne(filter, update);

                result = 0;
            }
            cursor.close();
        }
        return result;
    }

    /**
     * 四舍五入方式得到最多小数点后一位的数字表达（字符串）
      * @param src
     * @return
     */
    public static String getFormattedScore(Double src) {
        DecimalFormat decimalFormat = new DecimalFormat("#.#");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        return decimalFormat.format(src);
    }

    public static Map<Character, String> secretMap = new HashMap<Character, String>() {{
        put('1', "&#xec56;");
        put('2', "&#xe900;");
        put('3', "&#xe804;");
        put('4', "&#xe800;");
        put('5', "&#xee33;");
        put('6', "&#xe911;");
        put('7', "&#xe808;");
        put('8', "&#xec98;");
        put('9', "&#xeb54;");
        put('0', "&#xea03;");
        put('.', "&#xe901;");
    }};


    /**
     * 经过加密的字符串
     * @param src，双精度数字
     * @return 经过加密的字符串
     */
    public static String getFormattedSecretScore(Double src) {
        String temp = getFormattedScore(src);

        String result = "";
        for (int i = 0; i < temp.length(); ++i) {
            char c = temp.charAt(i);
            result += secretMap.get(c);
        }

        return result;
    }
}
